#include "stdafx.h"
#include "crc16.h"

char * command_info[num_command] =
{
	"heart beat received\n",
	"need start downloading program now\n",
	"download is completed now\n",
	"update successfully\n",
	"update failed\n"
};

void InvertUint8(unsigned char *DesBuf, unsigned char *SrcBuf)
{
	int i;
	unsigned char temp = 0;

	for (i = 0; i < 8; i++)
	{
		if (SrcBuf[0] & (1 << i))
		{
			temp |= 1 << (7 - i);
		}
	}
	DesBuf[0] = temp;
}

void InvertUint16(unsigned short *DesBuf, unsigned short *SrcBuf)
{
	int i;
	unsigned short temp = 0;

	for (i = 0; i < 16; i++)
	{
		if (SrcBuf[0] & (1 << i))
		{
			temp |= 1 << (15 - i);
		}
	}
	DesBuf[0] = temp;
}

unsigned short CRC16_MODBUS(unsigned char *puchMsg, unsigned int usDataLen)
{
	unsigned short wCRCin = 0xFFFF;
	unsigned short wCPoly = 0x8005;
	unsigned char wChar = 0;

	while (usDataLen--)
	{
		wChar = *(puchMsg++);
		InvertUint8(&wChar, &wChar);
		wCRCin ^= (wChar << 8);

		for (int i = 0; i < 8; i++)
		{
			if (wCRCin & 0x8000)
			{
				wCRCin = (wCRCin << 1) ^ wCPoly;
			}
			else
			{
				wCRCin = wCRCin << 1;
			}
		}
	}
	InvertUint16(&wCRCin, &wCRCin);
	return (wCRCin);
}

void CRC16_MODBUS_m(unsigned short *crc16_reg, unsigned char *puchMsg, unsigned int usDataLen)
{
	unsigned short wCRCin = *crc16_reg;
	unsigned short wCPoly = 0x8005;
	unsigned char wChar = 0;

	while (usDataLen--)
	{
		wChar = *(puchMsg++);
		InvertUint8(&wChar, &wChar);
		wCRCin ^= (wChar << 8);

		for (int i = 0; i < 8; i++)
		{
			if (wCRCin & 0x8000)
			{
				wCRCin = (wCRCin << 1) ^ wCPoly;
			}
			else
			{
				wCRCin = wCRCin << 1;
			}
		}
	}
	//InvertUint16(&wCRCin, &wCRCin);

	*crc16_reg = wCRCin;
	//return (wCRCin);
}

int findCommand(unsigned char * buff, int lengthIn)
{
	int i = 0, j = 0;
	unsigned short temp16 = 0;
	int retVal = -1;
	for (i = 0; i < lengthIn; i++)
	{
		if ((buff[i] & 0x00ff) == 0x00fe)
		{
			break;
		}
	}
	if (i >= lengthIn)
	{
		return retVal;
	}
	temp16 = (buff[i] & 0x00ff);
	switch (temp16)
	{
		case 0x00fe:
			retVal = 0;
			break;
		case 0x00fc:
			retVal = 1;
			break;
		case 0x00fb:
			retVal = 2;
			break;
		case 0x00fa:
			retVal = 3;
			break;
		case 0x00f0:
			retVal = 4;
			break;
		default:
			retVal = -1;
			break;
	}
	return retVal;
}